fix: handle zero and negative numbers in RadixSort#2184
Open
huizixin wants to merge 1 commit into
Open
Conversation
…Element Math.log10(0) returns -Infinity and Math.log10(-N) returns NaN, causing the sorting loop to never execute for arrays containing only zeros or negative numbers. Added early return for edge cases where max value is 0 or negative.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug Description
RadixSort.getLengthOfLongestElement()fails when the input array contains only zeros or negative numbers:Math.log10(0)returns-Infinity, causingnumPassesto be-InfinityMath.log10(-N)returnsNaN, causingnumPassesto beNaNIn both cases, the sorting loop (
for (let currentIndex = 0; currentIndex < numPasses; ...)) never executes, and the unsorted array is returned as-is.Steps to Reproduce
Fix
Added an early return in
getLengthOfLongestElement()to handle edge cases where the maximum value is 0 or negative:Testing
The existing test suite (
SortTester.testSort) includes[3, 4, 2, 1, 0, 0, 4, 3, 4, 2]which works correctly. However, arrays of purely negative numbers are not tested and reveal this bug.Note: Radix Sort has inherent limitations with negative numbers. A complete fix would require splitting the array by sign and merging results. This PR addresses the immediate
NaN/-Infinityissue to prevent silent incorrect behavior.